import { createRouter, createWebHistory } from 'vue-router'
import store from '../store'

import Login from '../pages/Login.vue'
import Register from '../pages/Register.vue'
import Home from '../pages/Home.vue'
import Recommend from '../pages/Recommend.vue'
import Category from '../pages/Category.vue'
import Search from '../pages/Search.vue'
import Post from '../pages/Post.vue'
import Publish from '../pages/Publish.vue'
import Profile from '../pages/Profile.vue'
import Admin from '../pages/Admin.vue'
import UserManage from '../components/UserManage.vue'
import CategoryManage from '../components/CategoryManage.vue'
import PostManage from '../components/PostManage.vue'
import ResourceManage from '../components/ResourceManage.vue'
import MessageManage from '../components/MessageManage.vue'
import SystemMonitor from '../components/SystemMonitor.vue'

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  { path: '/register', component: Register },
  { path: '/home', component: Home, meta: { requiresAuth: true } }, // 路由守卫 确保用户在登录后才能访问页面
  { path: '/recommend', component: Recommend, meta: { requiresAuth: true } },
  { path: '/category/:categoryId', name: 'category', component: Category, meta: { requiresAuth: true } },
  { path: '/post/:id', component: Post, meta: { requiresAuth: true } },
  { path: '/search', component: Search, meta: { requiresAuth: true } },
  { path: '/publish', component: Publish, meta: { requiresAuth: true } },
  { path: '/profile', component: Profile, meta: { requiresAuth: true } },
  { path: '/admin', component: Admin, meta: { requiresAuth: true }, children: [{
      path: 'user-management',
      component: UserManage
    }, {
      path: 'category-management',
      component: CategoryManage
    }, {
      path: 'post-management',
      component: PostManage
    }, {
      path: 'resource-management',
      component: ResourceManage
    }, {
      path: 'message-management',
      component: MessageManage
    }, {
      path: 'system-monitoring',
      component: SystemMonitor
    }]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth) && !store.getters.isAuthenticated) {
    next('/login')
  } else {
    next()
  }
})

export default router